package cn.com.miao.lynx.common.secure.config;

import cn.com.miao.lynx.common.core.constant.ResultStatus;
import cn.com.miao.lynx.common.core.model.Result;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ContentUrlBlockHandler
 * Sentinel规则错误提示优化
 * @title: ContentUrlBlockHandler
 * @description:
 * @author: dengmiao
 * @create: 2020-01-03 16:43
 **/
@Component
public class ContentUrlBlockHandler implements UrlBlockHandler {

    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        Result result;
        // 根据异常类型区分违反哪种规则
        // 限流异常
        if(e instanceof FlowException) {
            result = Result.error(ResultStatus.SENTINEL_DEGRADE_ERROR);
        }
        // 降级异常
        else if(e instanceof DegradeException) {
            result = Result.error(ResultStatus.SENTINEL_DEGRADE_ERROR);
        }
        // 热点参数异常
        else if(e instanceof ParamFlowException) {
            result = Result.error(ResultStatus.SENTINEL_PARAM_ERROR);
        }
        // 系统规则异常
        else if(e instanceof SystemBlockException) {
            result = Result.error(ResultStatus.SENTINEL_SYSTEM_ERROR);
        }
        // 认证异常
        else if(e instanceof AuthorityException) {
            result = Result.error(ResultStatus.SENTINEL_AUTHORITY_ERROR);
        }
        else {
            result = Result.error(ResultStatus.SENTINEL_ERROR);
        }
        Result.response(httpServletResponse, result);
    }
}
